<?php

class Mail
{

    private $_from;
    private $_fromName;
    private $_subject;
    private $_body;
    private $_addressList;
    private $_provider;

    public function __construct($provider)
    {
	$this->_provider = $provider;		
	$this->_init();
    }

    public function setFrom($from)
    {
	$this->_from = $from;
	return $this;
    }

    public function getFrom()
    {
	return $this->_from;
    }

    public function setFromName($fromName)
    {
	$this->_fromName = $fromName;
	return $this;
    }

    public function getFromName()
    {
	return $this->_fromName;
    }

    public function setSubject($subject)
    {
	$this->_subject = $subject;
	return $this;
    }

    public function getSubject()
    {
	return $this->_subject;
    }

    public function setBody($body)
    {
	$this->_body = $body;
	return $this;
    }

    public function getBody()
    {
	return $this->_body;
    }

    public function setAddressList($addressList)
    {
	$this->_addressList = $addressList;
	return $this;
    }
    public function addAddress($address)
    {
	if (!$address) {
	    return false;
	}
	$addressList = $this->getAddressList();
	array_push($addressList, $address);
	$this->setAddressList($addressList);
	return $this;
    }

    public function getAddressList()
    {
	if ($this->_addressList === null) {
	    $this->_addressList = array();
	}
	return $this->_addressList;
    }

    public function setProvider($provider)
    {
	$this->_provider = $provider;
	return $this;
    }

    public function getProvider()
    {
	return $this->_provider;
    }

    private function _init()
    {
	$mailConfig = Yii::app()->params['mail'];
	if (empty($mailConfig)) {
	    return false;
	}
	foreach ($mailConfig as $key => $value) {
	    if (isset($this->$key)) {
		$this->$key = $value;
	    }
	}
    }

    public function send()
    {
	$addressList = $this->getAddressList();
	
	if (empty($addressList)) {
	    return false;
	}
	$subject = $this->getSubject();	
	$body = $this->getBody();	
	if (!$subject || !$body) {
	    return false;
	}
	
	$provider = $this->getProvider();		
	if (!$provider) {
	    return false;
	}
	
	$addressList = array_unique($addressList);
	$provider->From = $this->getFrom();
	$provider->FromName = $this->getFromName();
	$provider->Subject = $this->getSubject();
	$provider->Body = $this->getBody();
	foreach ($addressList as $address) {
	    $provider->AddAddress($address);
	}
	
	return $provider->Send();
    }

}
